# _*_ encoding: utf-8 _*_
# 异步更新主体数据

import os
import sys
import yaml
import time
import random
import asyncio
from threading import Thread
from collections import deque
from db_config import connect_mysql


def get_location(config):
    db = connect_mysql(config)
    db.execute_sql("select * from devices")
    r = db.get_data()
    db.close_oracle()
    return r


async def exec_sync(configs, start_time):
    exec_time = time.time()
    print("开始时间：%s, 执行时间：%s, 时间差：%s" % (start_time, exec_time, (exec_time - start_time)))

    r = get_location(configs)
    print("获取一次mysql——data")
    return r


def dp_consumer(interval, dq):
    # 休眠时间投递一个信号
    while True:
        print("%s 休眠。。。" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        time.sleep(interval)
        i = random.randint(1, 10)
        dq.appendleft(str(i))


def tracking():
    """主题逻辑代码"""
    print("tracking...")
    pass


def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


# 主程序
def main():
    config_file = open(os.path.dirname(os.path.abspath(__file__)) + '/config.yaml')
    config = yaml.safe_load(config_file)

    # 休眠时间
    interval = 5
    # 要异步更新的数据主体
    loc_list = [1, 2, 3]

    start_time = time.time()

    dq = deque()
    thread_lst = []
    new_loop = asyncio.get_event_loop()
    t = Thread(target=start_loop, args=(new_loop,))
    thread_lst.append(t)
    c = Thread(target=dp_consumer, args=(interval, dq))
    thread_lst.append(c)

    for t in thread_lst:
        t.start()

    while 1:
        exec_time = time.time()
        print("--------------------%s-------------------------" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        tracking()
        if dq:
            msg = dq.pop()
            if msg:
                print(msg)
                box = asyncio.run_coroutine_threadsafe(exec_sync(config['mysql_local'], start_time), new_loop)
                start_time = exec_time
                loc_list = box.result()

        time.sleep(0.1)


if __name__ == '__main__':
    main()
